/**
 * Created by CJB on 2017/2/20.
 */

//===============================
//工具方法  Start
//===============================
/**
 * jquery黏贴事件
 * @param delay
 * @returns {*|jQuery}
 */
$.fn.pasteEvents = function( delay ) {
    if (delay == undefined) delay = 20;
    return $(this).each(function() {
        var $el = $(this);
        $el.on("paste", function() {
            $el.trigger("prepaste");
            setTimeout(function() { $el.trigger("postpaste"); }, delay);
        });
    });
};

/**
 * 获取当前项目完整路径
 * @returns {string}
 */
function getPath() {
    //获取当前网址
    var curPath = window.document.location.href;
    //获取主机地址后的目录
    var pathName = window.document.location.pathname;
    var pos = curPath.indexOf(pathName);
    //获取主机地址
    var localhostPath = curPath.substring(0, pos);
    //获取项目名称
    var projectName = pathName.substring(0, pathName.substr(1).indexOf("/") + 1);
    return localhostPath + projectName + "/";
}

//实现js的repalceAll方法
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};

/**
 * 生产uuid
 * @returns {string}
 */
function uuid() {
    var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var chars = CHARS, uuid = new Array(36), rnd=0, r;
    for (var i = 0; i < 36; i++) {
        if (i==8 || i==13 ||  i==18 || i==23) {
            uuid[i] = '-';
        } else if (i==14) {
            uuid[i] = '4';
        } else {
            if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
            r = rnd & 0xf;
            rnd = rnd >> 4;
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
    }
    return uuid.join('');
}

var commonTools = {
    clone: function (obj) {
        if (obj === null) return null;
        var o = commonTools.isArray(obj) ? [] : {};
        for (var i in obj) {
            o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]);
        }
        return o;
    },
    eqs: function (str1, str2) {
        return str1.toLowerCase() === str2.toLowerCase();
    }
    ,
    isArray: function (arr) {
        return Object.prototype.toString.apply(arr) === "[object Array]";
    }
}

/**
 * 获取窗口宽度
 * @returns {number}
 */
function getWindowWith(){
    var winWidth = 0;
    if(window.innerWidth)
        winWidth = window.innerWidth;
    else if((document.body) && (document.body.clientWidth))
        winWidth = document.body.clientWidth;
    else if((document.body) && (document.body.offsetWidth))
        winWidth = document.body.offsetWidth;
    if(document.documentElement && document.documentElement.clientWidth)
        winWidth = document.documentElement.clientWidth;
    return winWidth;
}

/**
 * 获取窗口高度
 * @returns {number}
 */
function getWindowHeight(){
    var winHeight = 0;
    if(window.innerHeight)
        winHeight = window.innerHeight;
    else if((document.body) && (document.body.clientHeight))
        winHeight = document.body.clientHeight;
    else if((document.body) && (document.body.offsetHeight))
        winHeight = document.body.offsetHeight;
    if(document.documentElement && document.documentElement.clientHeight)
        winHeight = document.documentElement.clientHeight;
    return winHeight;
}

//去除所有控件的虚线框
function removeBlur(){
    //文件选择框除外，否则无法单击选择文件
    $("a,button").bind("focus",function(){
        if(this.blur){
            this.blur();
        }
    });
}

/**
 * 有小数的加法计算
 * @param arg1
 * @param arg2
 * @returns {Number}
 */
function accAdd(arg1,arg2){
    var r1,r2,m;
    try{
        if(arg1.toString().indexOf(".") >= 0)
            r1=arg1.toString().split(".")[1].length;
        else
            r1 = 0;
    }catch(e){r1=0;}
    try{
        if(arg2.toString().indexOf(".") >= 0)
            r2=arg2.toString().split(".")[1].length;
        else
            r2 = 0;
    }catch(e){r2=0;}
    m=Math.max(r1,r2);
    if(m > 6)
        m = 6;
    return (parseInt(arg1*Math.pow(10,m))+parseInt(arg2*Math.pow(10,m)))/Math.pow(10,m);
}

/**
 * 有小数的减法计算
 * @param arg1
 * @param arg2
 * @returns {Number}
 */
function accDecrease(arg1,arg2){
    var r1,r2,m;
    try{
        if(arg1.toString().indexOf(".") >= 0)
            r1=arg1.toString().split(".")[1].length;
        else
            r1 = 0;
    }catch(e){r1=0;}
    try{
        if(arg2.toString().indexOf(".") >= 0)
            r2=arg2.toString().split(".")[1].length;
        else
            r2 = 0;
    }catch(e){r2=0;}
    m=Math.max(r1,r2);
    if(m > 6)
        m = 6;
    return (parseInt(arg1*Math.pow(10,m))-parseInt(arg2*Math.pow(10,m)))/Math.pow(10,m);
}

/**
 * 有小数的乘法计算
 * @param arg1
 * @param arg2
 * @returns {Number}
 */
function accMultiply(arg1,arg2){
    var r1,r2,m;
    try{
        if(arg1.toString().indexOf(".") >= 0)
            r1=arg1.toString().split(".")[1].length;
        else
            r1 = 0;
    }catch(e){r1=0;}
    try{
        if(arg2.toString().indexOf(".") >= 0)
            r2=arg2.toString().split(".")[1].length;
        else
            r2 = 0;
    }catch(e){r2=0;}
    m=Math.max(r1,r2);
    if(m > 6)
        m = 6;
    return (parseInt(arg1*Math.pow(10,m))*parseInt(arg2*Math.pow(10,m)))/Math.pow(10,2*m);
}

//===============================
//工具方法  End
//===============================
//===============================
//数据格式化  Start
//===============================
/** * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
 Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function(fmt) {
    var o = {
        "M+" : this.getMonth() + 1, // 月份
        "d+" : this.getDate(), // 日
        "h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
        "H+" : this.getHours(), // 小时
        "m+" : this.getMinutes(), // 分
        "s+" : this.getSeconds(), // 秒
        "q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
        "S" : this.getMilliseconds()// 毫秒
    };
    var week = {
        "0" : "/u65e5",
        "1" : "/u4e00",
        "2" : "/u4e8c",
        "3" : "/u4e09",
        "4" : "/u56db",
        "5" : "/u4e94",
        "6" : "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1,((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f": "/u5468"): "")+ week[this.getDay() + ""]);
    }
    for ( var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]): (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};
/**
 * 将字符串转成时间，格式为yyyy-MM-dd HH:mm:ss
 *
 * @param value
 */
function parseDateTime(value) {
    value = value.replace(/-/g, "/");
    var date = new Date(value);
    return date;
}
/**
 * 格式化表格的显示
 * @param value 值
 * @param format 如果是日期，进行日期格式化，如果不是，不填写
 * @returns {*}
 */
function formatResultItemText(value,options){
    options = $.extend({
        format: null,
        'default': '&nbsp;'
    },options || {});
    return value ? (options.format ? parseDateTime(value).pattern(options.format) : value) : options['default'];
}

/**
 * 限制为float
 * @param obj
 */
function keyUpFormatNumber(obj) {
    obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/^\./g,"");  //验证第一个字符是数字而不是.
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的.
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
}
/**
 * 限制wie数字
 * @param obj
 */
function keyUpFormatInteger(obj) {
    obj.value = obj.value.replace(/[^\d]/g,"");  //清除“数字”以外的字符
}
//===============================
//数据格式化  End
//===============================

//===============================
//表单  Start
//===============================

/**
 * 创建信息提示框
 * @param toolTips 保存所有的信息提示
 * @param atrgetID 目标控件
 * @returns {*} 信息提示控件
 */
function createTooltip(toolTips, atrgetID, options){
    options = $.extend({
        outside: 'x',
        fade: 0,
        pointer:true,
        initAutoOpen:false,
        autoOepn:true
    },options || {});
    var element = $("#" + atrgetID);
    var toolTip = toolTips[atrgetID];
    if(!toolTip){
        toolTip =   element.jBox('Tooltip', {
            id:atrgetID + "-error",
            position: {
                x: 'right',
                y: 'center'
            },
            outside: options.outside,
            fade: options.fade,
            pointer:options.pointer,
            delayOpen:500
        });
        element.trigger("mouseenter");
        if(!options.initAutoOpen)
            toolTip.close();
        toolTips[atrgetID] = toolTip;
    } else{
        if(options.autoOepn){
            toolTip.attach();
            element.trigger("mouseenter");
        }
    }
    return toolTip;
}

/**
 * 创建表头
 * @param tableId 表id
 * @param tableFields 表字段
 * {headerText:'',headerField:'',visible:true,minWidth:60,formatName:'formatResultItemText',dateFormat:'yyyy-mm-dd',fieldSate:0}
 * headerText 表格显示的标题
 * headerField 要显示的字段
 * visible 是否可见
 * minWidth 标题最小宽度
 * formatName 字段格式化的函数名称,函数包括formatResultItemText：格式化文本，可自定义，默认formatResultItemText
 * dateFormat 如果是日期，则进行格式化
 * fieldSate:0普通字段，1ID字段，2序号
 *checkType:1:checkbox,2:radio
 * checkAllId:当fieldSate=1时有用
 */
function createTableHeader(tableId,tableFields){
    var default_options = {formatName:'formatResultItemText',fieldSate:0,visible:true,checkAllId:'checkAll',checkType:1};
    var html = "<tr>";
    for(var x = 0; x < tableFields.length; x++) {
        var filed = tableFields[x];
        var options = commonTools.clone(default_options);
        options = $.extend(options,filed || {});
        if(options.fieldSate == 1){
            if(options.checkType == 1)
                html += '<th style="min-width: 30px;' + (options.visible ? '' : 'display:none;') + '"><span id="'+options.checkAllId+'" class="checkbox"></span></th>';
            else
                html += '<th style="min-width: 30px;' + (options.visible ? '' : 'display:none;') + '">'+filed.headerText+'</th>';
        }else if(options.fieldSate == 2){
            html += '<th style="min-width: 30px;">序号</th>';
        }else {
            var minWidth = filed.minWidth ? filed.minWidth : filed.headerText.length * 15;
            html += '<th style="min-width: '+minWidth+'px;' + (options.visible ? '' : 'display:none;') + '">'+filed.headerText+'</th>';
        }
    }
    html += "</tr>";
    $("#" + tableId).append(html);
}

/**
 * 创建表格内容
 * @param tableId 表id
 * @param tableFields 表字段
 * {headerText:'',headerField:'',visible:true,minWidth:60,formatName:'formatResultItemText',dateFormat:'yyyy-mm-dd',fieldSate:0,render:null}
 * headerText 表格显示的标题
 * headerField 要显示的字段
 * visible 是否可见
 * minWidth 标题最小宽度
 * formatName 字段格式化的函数名称,函数包括formatResultItemText：格式化文本，可自定义，默认formatResultItemText，其他函数只接受要显示的数值
 * dateFormat 如果是日期，则进行格式化
 * fieldSate:0普通字段，1:ID字段，2序号,如果是1，则使用selected字段,checkType字段
 * render:null,接受4个参数，第一个表头，第二个数据，第三个代表第几条数据，第四个表示第几个字段.
 * selected：true，false
 *checkType:1:checkbox,2:radio
 * @param page 分页数据
 */
function createTable(tableId,tableFields,page,tableOptions){
    tableOptions = $.extend({
        checkAllId:'checkAll',
        callback:null
    },tableOptions || {});
    var default_options = {formatName:formatResultItemText,fieldSate:0,visible:true,checkAllId:'checkAll',checkType:1};
    var list = page.items;
    if(list && list.length > 0){
        for(var i = 0; i < list.length; i++) {
            var item = list[i];
            var htmlObj = $("<tr" + ( i % 2 == 0 ? "" : " class='even'") + "></tr>");
            for(var x = 0; x < tableFields.length; x++){
                var filed = tableFields[x];
                var options = commonTools.clone(default_options);
                options = $.extend(options,filed || {});
                if(options.render){
                    var result = options.render(filed,item,i,x);
                    if(typeof (result) == "string"){
                        htmlObj.append("<td>" + result + "</td>");
                    }else{
                        var tdObj = $("<td></td>");
                        tdObj.append(result);
                        htmlObj.append(tdObj);
                    }
                }else{
                    if(options.fieldSate == 1){
                        htmlObj.append('<td style="' + (options.visible ? '' : 'display:none;') + '">' +
                            '<span id="' + item[filed.headerField] + '" name="' + filed.headerField +
                            '" class="' + (options.checkType == 1 ? 'checkbox' : 'radio') +
                            ' ' + (item.selected ? ' selected' : '') + '"></span></td>');
                    }else if(options.fieldSate == 2){
                        htmlObj.append('<td>' + (i + 1) + '</td>');
                    }else {
                        var formtFun = null;
                        if(typeof(options.formatName) == 'function')
                            formtFun = options.formatName;
                        else
                            formtFun = eval(options.formatName);
                        if(formtFun == formatResultItemText)
                            htmlObj.append('<td style="' + (options.visible ? '' : 'display:none;') + '">' + formtFun(item[filed.headerField],options.dateFormat) + '</td>');
                        else
                            htmlObj.append('<td style="' + (options.visible ? '' : 'display:none;') + '">' + formtFun(item[filed.headerField]) + '</td>');
                    }
                }
            }
            $("#" + tableId).append(htmlObj);
        }
    }
    for(var index = list.length; index < page.pageSize; index++){
        var htmlObj = $("<tr" + ( i % 2 == 0 ? "" : " class='even'") + "></tr>");
        for(var x = 0; x < tableFields.length; x++){
            htmlObj.append('<td></td>');
        }
        $("#" + tableId).append(htmlObj);
    }

    setGridListCheckBox(tableId,{
        filter:tableOptions.checkAllId,
        callback:tableOptions.callback
    })
}

/**
 * 返回创建分页插件的函数
 * @param pagId 分页插件id
 * @param tableId 表格id
 * @returns {Function}
 */
function createPagination(pagId, tableId, options){
    options = $.extend({
        loadListFunction:"loadList",
        visiblePages:10,
        first: '<li class="first"><a href="javascript:;">首页</a></li>',
        prev: '<li class="prev"><a href="javascript:;">上一页</a></li>',
        next: '<li class="next"><a href="javascript:;">下一页</a></li>',
        last: '<li class="last"><a href="javascript:;">尾页</a></li>',
        page: '<li class="page"><a href="javascript:;">{{page}}</a></li>',
        info:'<div class="info">显示第{{start}}到{{end}}条，共{{totalCounts}}条记录</div>',
        shotPage:false
    },options || {});
    var jqp;
    var queryParmas = {};
    var pageIndex = 1;
    var totalCount = 0;
    var pageSize = 10;
    var list = options.loadListFunction;
    if(options.loadListFunction && typeof (options.loadListFunction) == 'string')
        list = eval(options.loadListFunction);
    return function(page, params){
        queryParmas = params;
        if(!jqp){
            totalCount = page.totalCount;
            pageSize = page.pageSize;
            jqp = $.jqPaginator('#' + pagId, {
                visiblePages: options.visiblePages,
                currentPage: page.pageNumber,
                pageSize: page.pageSize,
                totalCounts: page.totalCount,
                first:options.first,
                prev:options.prev,
                next:options.next,
                last:options.last,
                page:options.page,
                info:options.info,
                shotPage:options.shotPage,
                onPageChange: function (num, type) {
                    if(num != pageIndex){
                        pageIndex = num;
                        list(tableId,num, pageSize,queryParmas);
                    }
                }
            });
        }else{
            pageSize = page.pageSize;
            jqp.jqPaginator("option",{
                pageSize:page.pageSize
            });
            pageIndex = page.pageNumber;
            totalCount = page.totalCount;
            jqp.jqPaginator("option",{
                currentPage:page.pageNumber,
                totalCounts:page.totalCount
            });
            if(totalCount == 0)
                $("#" + pagId).css('display','none');
            else
                $("#" + pagId).css('display','inline-block');
        }
        return jqp;
    };
}

function setGridListRadio(tableId, options){
    options = $.extend({
        callback:null
    },options || {});
    $("#"+tableId+" tr td span.radio").click(function(){
        if(!$(this).hasClass('selected')){
            $("#"+tableId+" tr td span.radio").removeClass('selected');
            $(this).addClass('selected');
            if(options.callback && typeof (options.callback) == 'function')
                options.callback({target:this});
        }
    });
}

/**
 * 设置表格的勾选框
 * @param tableId
 * @param options
 */
function setGridListCheckBox(tableId,options){
    options = $.extend({
        filter:'#checkAll',
        callback:null
    },options || {});
    setGridSelectAll(tableId, options);
    setGridSelectClick(tableId, options);
}

/***
 * 点击全选,判断是全选还是取消全选
 * tableId---表格id
 */
function setGridSelectAll(tableId, options){
    options = $.extend({
        filter:'#checkAll',
        callback:null
    },options || {});
    //点击全选,判断是全选还是取消全选
    $("#"+tableId+" " + options.filter).click(function(){
        if(!$(this).hasClass('selected')){
            $(this).addClass('selected');
            $("#"+tableId+" tr td span.checkbox").addClass('selected');
            if(options.callback && typeof (options.callback) == 'function'){
                var selectList = [];
                $("#"+tableId+" tr td span.checkbox").each(function(index){
                    selectList[index] = $(this).attr('id');
                });
                options.callback({target:this,selectList:selectList,removeList:[]});
            }
        }else{
            $(this).removeClass('selected');
            $("#"+tableId+" tr td span.checkbox").removeClass('selected');
            if(options.callback && typeof (options.callback) == 'function'){
                var removeList = [];
                $("#"+tableId+" tr td span.checkbox").each(function(index){
                    removeList[index] = $(this).attr('id');
                });
                options.callback({target:this,selectList:[],removeList:removeList});
            }
        }
    });
}

/***
 * 复选框选择改变，设置此行的样式，并判断当前情况是否为全选的情况
 * tableId---表格id
 */
function setGridSelectClick(tableId, options){
    options = $.extend({
        filter:'#checkAll',
        callback:null
    },options || {});
    $("#"+tableId+" tr td span.checkbox").click(function(){
        if($(this).hasClass('selected')){
            $(this).removeClass('selected');
            $(options.filter).removeClass('selected');
            if(options.callback && typeof (options.callback) == 'function'){
                options.callback({target:this,selectList:[],removeList:[$(this).attr('id')]});
            }
        }else{
            $(this).addClass('selected');
            var allLen = $("#"+tableId+" tr td span.checkbox").length;
            var selectedLen = $("#"+tableId+" tr td span.checkbox.selected").length;
            if(allLen == selectedLen)
                $(options.filter).addClass('selected');
            if(options.callback && typeof (options.callback) == 'function'){
                options.callback({target:this,selectList:[$(this).attr('id')],removeList:[]});
            }
        }
    });
}

/**
 * 双击查看详情
 * @author cfb
 * tableId 点击的表单ID
 * dialogId 弹窗DIV的Id
 * url
 */
function setGridDetailDbClick(tableId, url, options){
    options = $.extend({
        dialogId:'detailDialog'
    },options || {});
    $("#" + tableId + " tr:gt(0)").dblclick(function(){
        var id = $(this).find("td:first-child span.checkbox").attr("id");
        if(id){
            $("#" + options.dialogId).load(getPath() + url + '/' + id);
        }
    })
}

/**
 *  初始化修改记录
 * @author cfb
 * logId 查询记录的日志ID
 * logTime 日志时间
 * url
 * logDivId 修改日志显示的DIV
 */
function setGridDetailFormat(logId, options){
    options = $.extend({
        url:'app/logChange/list',
        logTime:null,
        logDivId:'',
        fields:[]
    },options || {});
    if(logId){
        $("#li"+logId).addClass("selectedLi");
        post(getPath() + options.url + '/' + logId,{logTime:options.logTime},
            function(resultObject){
                var logChangeArr = resultObject.logChangelist;
                var logInfo = "<span style='color: red;'>"+options.logTime+"修改内容:</span><br/>";
                if(logChangeArr.length >0){
                    for ( var i = 0; i < logChangeArr.length; i++) {
	                        var item = logChangeArr[i];
	                        var field = options.fields[item.columnName];
	                        field = $.extend({
	                            name:'',
	                            visible:true,
	                            format:null
	                        },field || {});
	                        if(field.visible){
		                        logInfo += (i+1)+"、"+ item.userName +" 将  \""+ field.name +"\"  由  \"";
		                        if(item.oldRealValue){
		                            logInfo += item.oldRealValue;
		                        }else if(item.oldValue){
		                            logInfo += field.format ? field.format(item.oldValue, field) : item.oldValue;
		                        }else{
		                            logInfo +=" ";
		                        }
		                        logInfo += "\"  改为   \"";
		                        if(item.newRealValue){
		                            logInfo += item.newRealValue+"\"<br>";
		                        }else if(item.newValue){
		                            logInfo += field.format ? field.format(item.newValue, field)+"\"<br>" : item.newValue+"\"<br>";
		                        }else{
		                            logInfo +="\" ";
		                        }
	                        }  
                        
                    }
                }

                $("#" + options.logDivId).append(logInfo);
            },function(message){
            	
            });

    }
}

/***
 * 点击查询
 */
function setSearchBtnClick(url, options){
    options = $.extend({
        searchBtnId:'searchBtn',//查询按钮id
        formId:"searchForm",
        filterId:'isFilter'
    },options || {});
    //点击查询
    $("#" + options.searchBtnId).click(searchFun);
    $('#' + options.formId + ' .search-input').keydown(function(event){
        if(event.which == 13){
            searchFun(event);
        }
    });

    function searchFun(event){
        if(options.searchBtnId && url && options.formId){
            if(options.filterId)
                $('#' + options.filterId).val(1);
            window.location.href = getPath() + url + $("#" + options.formId).serialize();
        }
        event.preventDefault();
    }
}

/**
 * 设置高级搜索功能
 * @param option
 */
function setAdvanceSearchBtnclick(options){
    options = $.extend({
        btnEle:$('.btn-arrow'),
        filterEle:$('.grid-filter')
    },options || {});
    options.btnEle.mouseover(function(event){
        if(options.filterEle.is(':hidden'))
            options.filterEle.show('fast');
        event.preventDefault();
        event.stopPropagation();
    });
    options.filterEle.find('input[type="radio"]').checkboxradio({
        icon:false
    });
    options.filterEle.find('input[type="checkbox"]').checkboxradio({
        icon:false
    });
    $("body").bind("mousedown", hideAdvanceFilter);
    /**
     * 隐藏树形菜单
     * @param event
     */
    function hideAdvanceFilter(event) {
        if ($(event.target).parents('.grid-filter').length == 0) {
            options.filterEle.hide('fast');
        }
    }
}

/***
 * 打开添加窗口
 * tableId---表格id
 * url---打开添加页面的url
 */
function setAddBtnClick(url,options){
    options = $.extend({
        targetBtn:$("#addBtn"),
        dialogId:"dialog",
        loadDivId:"loadDiv",
        emptyList:[]//清空内容id
    },options || {});
    options.targetBtn.click(function (event) {
        if(options.emptyList && options.emptyList.length > 0){
            for(var i= 0 ; i < options.emptyList.length; i++){
                $("#" + options.emptyList[i]).empty();
            }
        }
        if(options.dialogId)
        	$("#"+options.loadDivId).loading().showLoading();
            $("#" + options.dialogId).load(getPath() +url,function(){
            	$("#"+options.loadDivId).loading().hideLoading();
            });
        event.preventDefault();
    });
}

/***
 * 打开添加窗口
 * tableId---表格id
 * url---打开添加页面的url
 */
function setExportBtnClick(url,options){
    options = $.extend({
        exportBtnId:'exportBtn',//导出按钮id
        formId:"searchForm",
        tableId:"",
        loadDivId:"loadDiv"
    },options || {});
    //点击导出
    $("#" + options.exportBtnId).click(function(){
        var exportNum = $("#" + options.tableId + " tr td span.checkbox");
        if(exportNum.length >0){
        	 var selectList = new Array();
             $("#"+options.tableId+" tr td span.checkbox").each(function () {
                 if ($(this).hasClass('selected'))
                     selectList[selectList.length] = $(this).attr("id");
             });
             if(selectList.length == 0){
	            createWindow('确定导出列表中的数据吗？',{
	                width:220,
	                callBack:function(){
	                    //生成excel文件
	                	$("#"+options.loadDivId).loading().showLoading();
	                    post(getPath() + url, $("#"+options.formId).serialize() , function(path){
	                    	$("#"+options.loadDivId).loading().hideLoading();
	                        //下载excel文件
	                        window.open(getPath() + "app/file/download/temp?path=" + path);
	                    });
	                }
	            }).dialog('open');
             }else{
            	 var ids = selectList.join( "," );
            	 createWindow('确定导出勾选的数据吗？',{
 	                width:220,
 	                callBack:function(){
 	                    //生成excel文件
 	                	$("#"+options.loadDivId).loading().showLoading();
 	                    post(getPath() + url, {"exportIds":ids} , function(path){
 	                    	$("#"+options.loadDivId).loading().hideLoading();
 	                        //下载excel文件
 	                        window.open(getPath() + "app/file/download/temp?path=" + path);
 	                    });
 	                }
 	            }).dialog('open'); 
             }
        }else{
            createWindow('没有可导出的数据。',{width:220,height:160}).dialog('open');
        }
    });
}
/**
 * 列表编辑功能
 * @param url
 * @param options
 */
function gridDataEdit(url,options){
    options = $.extend({
        dialogId:"dialog",
        emptyList:[],//清空内容id
        loadDivId:"loadDiv"
    },options || {});
    if(options.emptyList && options.emptyList.length > 0){
        for(var i= 0 ; i < options.emptyList.length; i++){
            $("#" + options.emptyList[i]).empty();
        }
    }
    if(options.dialogId){
    	var loadDiv = $("#"+options.loadDivId).loading();
    	loadDiv.showLoading();
        $("#" + options.dialogId).load(getPath() +url,function(){
        	loadDiv.hideLoading();
        });
    }
}

function gridDataDelete(url,options){
    options = $.extend({
        multiple:false,//是否多选删除，false为单选的
        tableId:'',//多选删除用的表格
        deleteBtnId:'deleteBtn',//多选删除按钮
        loadDivId:'loadDiv',//数据加载提示Div
        deleteSuccess:function(resultObject){
            if(options.successUrl){
            	$("#"+options.loadDivId).loading().hideLoading();
                createWindow(resultObject,{url:getPath() + options.successUrl + ($("#" + options.filterId).val() == 1 ? ("?" + $("#" + options.formId).serialize()) : "")}).dialog("open");
            }
            else{
            	$("#"+options.loadDivId).loading().hideLoading();
                createWindow(resultObject).dialog("open");
            }
        },//删除成功的回调
        successUrl:'',//删除成功的回调地址
        formId:'searchForm',
        filterId:'isFilter'
    },options || {});

    if(options.deleteSuccess && typeof (options.deleteSuccess) == 'string'){
        options.deleteSuccess = eval(options.deleteSuccess);
    }

    if(options.multiple){
        if(options.deleteBtnId && options.tableId)
            $("#" + options.deleteBtnId).click(function(event){
                event.preventDefault();
                var selectList = new Array();
                $("#"+options.tableId+" tr td span.checkbox").each(function () {
                    if ($(this).hasClass('selected'))
                        selectList[selectList.length] = $(this).attr("id");
                });
                if(selectList.length == 0){
                    createWindow('请选择要删除的数据').dialog('open');
                    return ;
                }
                createWindow('你确定要删除该数据？',{
                    cancleEnable:true,
                    callBack:function(){
                    	$("#"+options.loadDivId).loading().showLoading();
                        var ids = selectList.join( "," );
                        post(getPath() + url + ids,{}, options.deleteSuccess);
                    }
                }).dialog('open');
            })
    }else {
        createWindow('你确定要删除该数据？',{
            cancleEnable:true,
            callBack:function(){
            	$("#"+options.loadDivId).loading().showLoading();
                post(getPath() + url,{}, options.deleteSuccess);
            }
        }).dialog('open');
    }
}

//===============================
//表单  End
//===============================

//===============================
// Ajax  Start
//===============================
/**
 * 请求后台，主要用于解析后台返回数据
 * @param url 地址
 * @param data 参数
 * @param resultFun resultFun(result) result为解析后的结果，即this.getJson(isSuccess,result)中的result
 */
function post(url,data,resultFun,errorFun){
    $.post(url,data,function(data){
        var result = eval("(" + data + ")");
        if(result.isSuccess){
            var resultObject = result.resultObject;
            resultFun(resultObject);
        }else{
            if(errorFun){
                errorFun(result.resultObject);
            }else
                createWindow(result.resultObject).dialog('open');
        }
    });
}

/**
 * 请求后台，主要用于解析后台返回数据
 * @param url 地址
 * @param resultFun resultFun(result) result为解析后的结果
 * @param errorFun
 */
function getJson(url,resultFun,errorFun){
    $.getJSON(url, function(result){
        if(result.isSuccess){
            var resultObject = result.resultObject;
            resultFun(resultObject);
        }else{
            if(errorFun){
                errorFun(result.resultObject);
            }else
                createWindow(result.resultObject).dialog('open');
        }
    });
}

/**
 * 加载js
 * @param file
 * @param options
 */
function include_js(file,options) {
    options = $.extend({
        loadComplete:null
    },options || {});
    var _doc = document.getElementsByTagName('head')[0];
    var js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', file);
    _doc.appendChild(js);
    if (document.all) { //如果是IE
        js.onreadystatechange = function () {
            if (js.readyState == 'loaded' || js.readyState == 'complete') {
                if(options.loadComplete)
                    options.loadComplete();
            }
        }
    }
    else {
        js.onload = function () {
            if(options.loadComplete)
                options.loadComplete();
        }
    }
}

//===============================
// Ajax  End
//===============================

/**
 * 创建弹出窗口
 * @param label 要显示的文本
 * @param options 其他参数
 * @returns {jQuery|HTMLElement}
 */
function createWindow(label,options){
    options = $.extend({
        width: 200,
        height: 140,
        url: "",
        icon: "",
        callBack:null,
        cancleEnable:false,
        cancleCallBack:null,
        buttons: {
            ok:'',
            cancel:'gray'
        }
    },options || {});
    var defaultButtons = [
        {
            text:"确定",
            class:options.buttons.ok,
            click: function () {
                if(options.callBack){
                    $(this).dialog("close");
                    options.callBack();
                }else if(!options.url)
                    $(this).dialog("close");
                else
                    window.location.href = options.url;
            }
        }
    ];
    if(options.cancleEnable){
	        defaultButtons[1] = {
	            text:"取消",
	            class: options.buttons.cancel,
	            click: function () {
	                $(this).dialog("close");
	                if(options.cancleCallBack)
	                	options.cancleCallBack();
	            }
	        };
    }
    var promptWindow = $("<div><p class='dialog-content'>" + label + "</p></div>");
    promptWindow.appendTo("html");
    promptWindow.dialog({
        autoOpen: false,
        width: options.width,
        height: options.height,
        resizable: false,
        title: "系统提示",
        modal: true,
        close: function(){
            if(!options.url) {
//                $(this).dialog("close");
            } else
                window.location.href = options.url;
        }
    });
    promptWindow.dialog("option",{
        buttons: defaultButtons
    });
    return promptWindow;
}

/**
 * 设置自动填充
 * @param id
 * @param targetId
 * @param url
 * @param options
 */
function setAutoComplete(id, targetId, url, options){
    options = $.extend({
        key:"name",
        minLength:0,
        labelField:'label',
        valueField:'value',
        pageKey:'items',
        isPage:true,
        selectChange:null
    },options || {});
    $("#" + id).parent().append('<span id="' + id + '_show" class="button arrow-select" style="display:none"></span>');
    $("#" + id).parent().html("<div style='float: left;width: 100%;position: relative;'>"+$("#" + id).parent().html() +"</div>");
    $("#" + id).autocomplete({
        source:function(request, response){
            $("#" + targetId).val('');
            var postData = {};
            postData[options['key']] = request.term;
            post(url,postData,function(data){
                if(options.isPage)
                    data = data[options.pageKey];
                var list = [];
                if(data.length){
                    for(var i = 0; i < data.length; i++){
                        var item = data[i];
                        item.label = item[options.labelField];
                        item.value = item[options.labelField];
                        item.id = item[options.valueField];
                        list[i] = item;
                    }
                }
                //判断三角箭头的显示与隐藏
                if(list.length > 0)
                    $('#' + id + '_show').show();
                else
                    $('#' + id + '_show').hide();

                response(list);
            })
        },
        minLength:options.minLength,
        select:function(event, ui){
            $("#" + targetId).val(ui.item.id);
            if(options.selectChange)
                options.selectChange(ui.item);
        }
    });
    $("#" + id).focus(function(){
        $("#" + id).autocomplete('search',$("#" + id).val());
    });
    $('#' + id + '_show').click(function(){
        $("#" + id).trigger('focus');
        $("#" + id).autocomplete('search',$("#" + id).val());
    });
}

/**
 * 获取数据字典列表(适用于只有一级列表，不适用于树结构) lrs
 * @param selectId <select></select>的id
 * @param dictionaryCode 数据字典编码
 */
function getDictionaryList(selectId, dictionaryCode){
    if($("#" + selectId + " option").length == 0){
        post(getPath() + "app/dictionary/tree/" + dictionaryCode,{},
            function(resultObject){
                if(resultObject.length > 0){
                    var htmlStr = "";
                    for(var i=1; i < resultObject.length; i++){
                        var item = resultObject[i];
                        htmlStr += "<option value='" + item.id + "'>" + item.name + "</option>";
                    }
                    $("#" + selectId).html(htmlStr);
                }
            }
        );
    }
}

//===============================
// 弹出Ztree类型下拉框  Start
//===============================

/**
 * 点击节点时，反向选择
 * @param e
 * @param treeId
 * @param treeNode
 * @returns {boolean}
 */
function onZTreeMenuClick(e, treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj(treeId);
    zTree.checkNode(treeNode, !treeNode.checked, true, true);
    return false;
}
/**
 * 显示树形菜单
 * @params data 包含：menuContentId树的内容id，
 */
function showMenu(event) {
    var cityObj = $(this);
    var cityOffset = cityObj.offset();
    var options = $.extend({
        left:cityOffset.left,
        top:cityOffset.top + cityObj.outerHeight()
    },event.data || {});
    $("#" + event.data.menuContentId).css({left:options.left, top:options.top}).slideDown("fast");
    $("#" + event.data.menuContentId).offset({left:options.left, top:options.top});
    event.data.targetId = $(this).attr("id");
    $("body").bind("mousedown",event.data, onBodyDown);
}
/**
 * 隐藏树形次啊单
 */
function hideMenu(data) {
    $("#" + data.menuContentId).fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}
/**
 * 隐藏树形菜单
 * @param event
 */
function onBodyDown(event) {
    if (!(event.target.id == event.data.targetId || event.target.id == event.data.menuContentId || $(event.target).parents("#" + event.data.menuContentId).length>0)) {
        hideMenu(event.data);
    }
}

/**
 * 选择改变，改变输入框的显示
 * @param attachTargetId 触发事件的id，用于显示名称等文本
 * @param targetId 目标id，用于显示id，提交到后台
 */
function onZTreeCheck(attachTargetId, targetId){
    return function onCheck(e, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId),
            nodes = zTree.getCheckedNodes(true),
            v = "", ids = "";
        for (var i=0, l=nodes.length; i<l; i++) {
            v += nodes[i].name + ",";
            ids += nodes[i].id + ",";
        }
        if (v.length > 0 ) v = v.substring(0, v.length-1);
        if (ids.length > 0 ) ids = ids.substring(0, ids.length-1);
        var cityObj = $("#" + attachTargetId);
        cityObj.val(v);
        $("#" + targetId).val(ids);
    };
}

/**
 * 添加权限选择改变，改变输入框的显示
 * @param attachTargetId 触发事件的id，用于显示名称等文本
 * @param targetId 目标id，用于显示id，提交到后台
 */
function onDialogTreeOnClick(attachTargetId, targetId){
    return function onCheck(e, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        $("#" + attachTargetId).val(zTree.getNodeByTId(treeNode.tId).name);
        $("#" + targetId).val(zTree.getNodeByTId(treeNode.tId).id);
    };
}

//===============================
// 弹出Ztree类型下拉框  Start
//===============================

//===============================
// Ztree搜索和高亮 Start
//===============================
/**
 * 树查询,高亮显示并展示【模糊匹配搜索条件的树节点】
 * @author chm
 * @param treeId 树id
 * @param searchId 查询文本框的id
 */
function search_ztree(treeId,searchId){
    searchByFlag_ztree(treeId, searchId, "");
}

/**
 * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
 * @param treeId
 * @param searchConditionId		搜索条件Id
 * @param flag 					需要高亮显示的节点标识
 */
function searchByFlag_ztree(treeId, searchId, flag){
    //<1>.搜索条件
    var searchCondition = $('#'+searchId).val();
    //<2>.得到模糊匹配搜索条件的节点数组集合
    var highlightNodes = new Array();
    if(searchCondition != ""){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        highlightNodes = treeObj.getNodesByParamFuzzy("name",searchCondition);
    }
    highlightAndExpand_ztree(treeId, highlightNodes,flag);
}
/**
 * 高亮显示并展示【指定节点】
 * @param treeId
 * @param highlightNodes 需要高亮显示的节点数组
 * @param flag			 需要高亮显示的节点标识
 */
function highlightAndExpand_ztree(treeId, highlightNodes,flag){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    //<1>. 先把全部节点更新为普通样式
    var treeNodes = treeObj.transformToArray(treeObj.getNodes());
    for (var i = 0; i < treeNodes.length; i++) {
        treeNodes[i].highlight = false;
        treeObj.updateNode(treeNodes[i]);
    }
    //<2>.收起树, 只展开根节点下的一级节点
    //close_ztree(treeId);
    treeObj.expandAll(false);
    var node = treeObj.getNodes()[0];
    treeObj.expandNode(node,true);
    //<3>.把指定节点的样式更新为高亮显示，并展开
    if (highlightNodes != null) {
        for (var i = 0; i < highlightNodes.length; i++) {
            //高亮显示节点，并展开
            highlightNodes[i].highlight = true;
            treeObj.updateNode(highlightNodes[i]);
            //高亮显示节点的父节点的父节点....直到根节点，并展示
            var parentNode = highlightNodes[i].getParentNode();
            var parentNodes = getParentNodes_ztree(parentNode);
            treeObj.expandNode(parentNodes, true, false, true);
            treeObj.expandNode(parentNode, true, false, true);
        }
    }
}

/**
 * 收起树：只展开根节点下的一级节点
 * @param treeId
 */
function close_ztree(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.transformToArray(treeObj.getNodes());
    var nodeLength = nodes.length;
    for (var i = 0; i < nodeLength; i++) {
        if (nodes[i].id == '0') {
            //根节点：展开
            treeObj.expandNode(nodes[i], true, true, false);
        } else {
            //非根节点：收起
            treeObj.expandNode(nodes[i], false, true, false);
        }
    }
}

/**
 * 递归得到指定节点的父节点的父节点....直到根节点
 */
function getParentNodes_ztree(node){
    if (node && node.getParentNode()) {
        return getParentNodes_ztree(node.getParentNode());
    } else {
        return node;
    }
}

/**
 * 设置树节点字体样式
 */
function setFontCss_ztree(treeId, treeNode) {
    if (treeNode.isParent == false){
        //叶子节点
        return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#666666", "font-weight":"normal"};
    } else {
        //父节点
        return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#666666", "font-weight":"bold"};
    }
}
//===============================
// Ztree搜索和高亮 End
//===============================


//左边树的高度,适合所有页面
function setZTreeHeight(options){
	options = $.extend({
        el:"#treeDiv",
        filterEl:'.grid-toolbar',
        otherHeight:115
    },options || {});
    $(options.el).css("height",getWindowHeight()-$(options.filterEl).height() - options.otherHeight);
    window.onresize = function(){
        $(options.el).css("height",getWindowHeight()-$(options.filterEl).height() - options.otherHeight);
    }
}

//===============================
// jquery validate验证器扩展 START
//===============================
/**
 * 添加下拉列表选择框的判断，必选
 */
function addSelectValidator(){
    $.validator.addMethod(
        "select",
        function(value, element){
            if(!value){
                return false;
            }else{
                return true;
            }
        },
        "必须选择一项"
    );
}
//固定电话验证 
function isTellPhoneValidator(){
    jQuery.validator.addMethod("isTellPhone", function(value,element) {
        if(value){
            var tel = /^(\d{3,4}-)?\d{7,8}$/; //固话号
            return this.optional(element) || (tel.test(value));
        }else{
            return true;
        }
    }, "请正确填写固定电话，例：区号-号码");
}
//手机号验证
function isCellPhoneValidator(){
    jQuery.validator.addMethod("isCellPhone", function(value,element) {
        if(value){
            var mobile = /^1[34578]\d{9}$/; //手机号
            return this.optional(element) || (mobile.test(value));
        }else{
            return true;
        }
    }, "请正确填写手机号");
}

//验证字符长度
function strLengthValidator(){
    jQuery.validator.addMethod("strMaxLenth", function(value,element,param) {
        if(value){
            var len = value.length;
            var reLen = 0;
            var charCode = -1;
            for ( var i = 0; i < len; i++) {
                charCode = value.charCodeAt(i);
                if(charCode >= 0 &&charCode <= 128){
                    reLen +=1;
                }else{
                    reLen +=3;
                }
            }
            return this.optional(element) || ( reLen <= param );
        }else{
            return  true;
        }
    }, "内容长度过长");
}

//验证邮政编码
function zipCodeValidator(){
    jQuery.validator.addMethod("zipCode", function(value,element) {
        if(value){
            var zip = /^[0-9]{6}$/;
            return this.optional(element) || (zip.test(value));
        }else{
            return true;
        }
    }, "邮政编码格式错误");
}

//验证传真
function faxValidator(){
    jQuery.validator.addMethod("formatFax", function(value,element) {
        if(value){
            var fax = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
            return this.optional(element) || (fax.test(value));
        }else{
            return true;
        }
    }, "传真格式错误");
}
/**
 * 自动填充验证
 */
function autocompleteValidator(){
    jQuery.validator.addMethod("autocomplete", function(value,element,params) {
        var content = $("#"+ params[0]).val();
        var contentId = $("#"+ params[1]).val();
        if(contentId || !content ){
            return true;
        }else{
            return false;
        }
    }, "请输入关键字进行选择");
}
//===============================
// jquery validate验证器扩展 END
//===============================

/**
 * 添加通道监听
 * @param channelName 通道名称
 * @param channelFun 处理方法
 */
function addComet4jListener(options) {
	options = $.extend({
		comet4jObject: window.top.comet4jObject || JS,
		channelName: "",
		channelFun: function(){}
	}, options || {});
	if(!options.comet4jObject) {
		return false;
	}
	options.comet4jObject.Engine.addListener(options.channelName, options.channelFun);
	if(options.comet4jObject.Engine.running === false) {
		options.comet4jObject.Engine.start(getPath()+'conn');
	}
	return options.comet4jObject;
}